import GameUtil from "./GameUtil";
import { IGuestData } from "./IMessage";
import SceneGame, { EItemType } from "./SceneGame";

const { ccclass, property } = cc._decorator;

const MAX_WIDTH: number = 70;
const MAX_HEIGHT: number = 120;
const DISTANCE: number = 180;   // 顾客间距

enum EAnimType {
    DaiJi = 'daiji',
    Xiao = 'xiao',
}

@ccclass
export default class ItemGuest extends cc.Component {

    @property({ type: sp.Skeleton, tooltip: "人物动画" })
    private ske: sp.Skeleton = null;

    @property({ type: [cc.Node], tooltip: "影子" })
    private shadows: cc.Node[] = [];

    @property({ type: cc.Node, tooltip: "气泡" })
    private bubble: cc.Node = null;

    @property({ type: cc.Node, tooltip: "锁子" })
    private lock: cc.Node = null;

    private isMove: boolean = false;

    private data: IGuestData = null;

    public setData(data: IGuestData) {
        this.data = data;
        if (!data.isLock && data.itemId < 0) {
            data.itemId = SceneGame.instance.getSpeciesId1();
        }

        this.lock.active = data.isLock;
        this.ske.node.active = !this.lock.active;
        this.bubble.scale = 0;
        this.node.x = !data.isLock ? 600 + DISTANCE * data.id : -240 + DISTANCE * data.id;
        this.node.active = data.itemId != null;

        if (!data.isLock) {
            this.moveGuest();
        }

        if (data.isLock) {
            this.shadows[0].active = data.id === 2;
            this.shadows[1].active = data.id === 3;
        }

        this.lock.on(cc.Node.EventType.TOUCH_END, this.onLockBtnClicked, this);
        this.bubble.on(cc.Node.EventType.TOUCH_END, this.onBubbleBtnClicked, this);
    }

    public refreshUI() {
        if (!this.data) return;

        if (this.data.cur >= this.data.max) {
            this.data.itemId = -1;

            const complete = () => {
                const cb = () => {
                    this.node.stopAllActions();
                    cc.tween(this.node).sequence(
                        cc.moveTo(1, cc.v2(-1000, this.node.y)),
                        cc.callFunc(() => {
                            this.data.cur = 0;
                            this.data.itemId = SceneGame.instance.getSpeciesId1();
                            this.data.ske = GameUtil.instance.getGuestSkeData();
                            this.refreshBubble();

                            this.node.active = this.data.itemId != null;
                            this.moveGuest();

                            // 结束检测
                            SceneGame.instance.checkGameResult();
                        }),
                    ).start();
                }

                cc.tween(this.bubble).sequence(
                    cc.scaleTo(0.3, 0),
                    cc.callFunc(() => {
                        this.ske.setAnimation(0, EAnimType.DaiJi, true);
                    }),
                    cc.delayTime(1),
                    cc.callFunc(() => {
                        cb && cb();
                    }),
                ).start();
            }

            this.ske.setAnimation(0, EAnimType.Xiao, false);
            this.ske.setCompleteListener((trackEntry, loopCount) => {
                if (trackEntry.animation.name === EAnimType.Xiao) {
                    SceneGame.instance.flyToProgress(this.node, this.data.itemId);
                    complete && complete();
                }
            });
        }

        this.updateColor();
    }

    private moveGuest() {
        if (this.data.isLock || !this.data) {
            return;
        }

        try {
            if (this.ske.node.active) {
                const self = this;
                cc.resources.load(`spine/${this.data.ske.name}`, sp.SkeletonData, (err, skeData) => {
                    if (err) {
                        cc.error(err.message || err);
                        return;
                    }
                    self.ske.node.y = this.data.ske.y;
                    self.ske.skeletonData = skeData;
                    self.ske.premultipliedAlpha = false;
                    self.ske.setAnimation(0, EAnimType.DaiJi, true);
                });
            }
        } catch (error) {
            console.log(error);
        }

        this.isMove = true;
        this.node.x = 600 + DISTANCE * this.data.id;
        this.node.stopAllActions();
        cc.tween(this.node).sequence(
            cc.delayTime(0.5 * this.data.id),
            cc.moveTo(1, cc.v2(-240 + DISTANCE * this.data.id, this.node.y)).easing(cc.easeBackIn()),
            cc.callFunc(() => {
                this.showBubble();
            }),
        ).start();

        if (GameUtil.isTest) {
            this.bubble.children.forEach((o) => {
                cc.find("lab", o).getComponent(cc.Label).string = `${this.data.itemId}`;
            });
        }
    }

    private showBubble() {
        this.isMove = false;
        this.bubble.stopAllActions();
        cc.tween(this.bubble).sequence(
            cc.scaleTo(0.5, 0.7, 0.7).easing(cc.easeBackInOut()),
            cc.callFunc(() => {
                this.refreshBubble();
                // 暂存区到顾客
                SceneGame.instance.tempToGuest(this.data.itemId);
            }),
        ).start();
    }

    private refreshBubble() {
        this.bubble.children.forEach((o, i) => {
            const cb = () => {
                o.stopAllActions();
                cc.tween(o).repeatForever(
                    cc.sequence(
                        cc.scaleTo(1, o.scale * 1.2, o.scale * 1.2).easing(cc.easeSineOut()),
                        cc.scaleTo(1, o.scale * 1, o.scale * 1).easing(cc.easeSineIn()),
                    ),
                ).start();
            }
            const sprite = o.getComponent(cc.Sprite);
            GameUtil.instance.setItemIcon(EItemType.Guest, this.data.itemId, sprite, MAX_WIDTH, MAX_HEIGHT, cb);
        });

        this.updateColor();
    }

    private updateColor() {
        if (!this.data) return;
        try {
            this.bubble.children.forEach((o, i) => {
                const color = GameUtil.instance.getColorByState(i < this.data.cur);
                o.color = new cc.Color().fromHEX(color);
            });
        } catch (error) {
            console.log(error, this.data.id);
        }
    }

    public getFlyToNode() {
        if (!this.data) return;
        const node = this.bubble.children[this.data.cur];
        this.data.cur++;
        if (this.data.cur > this.data.max) {
            return null;
        }
        return node;
    }

    public getIsMove() {
        return this.isMove;
    }

    private onBubbleBtnClicked(event: cc.Event, data: cc.Event.EventCustom) {
        if (this.isMove) {
            console.log("移动中点击无效!!!");
            return;
        }

        SceneGame.instance.shakeTip(this.data.itemId);
    }

    private onLockBtnClicked(event: cc.Event, data: cc.Event.EventCustom) {
        if (this.data.isLock) {
            this.data.itemId = SceneGame.instance.getSpeciesId1();
            this.data.isLock = false;
            this.setData(this.data);
        }
    }
}